/* eslint-disable */
import axios from 'axios'
import url from '@/components/js/urlconfig'
import comonhelper from '@/components/js/comhelper.js'
// import Vue from 'vue'
import qs from 'qs'
// import { md5 } from 'vux'
import md5 from 'js-md5';
import moment from 'moment'
import store from '@/store/store'

// const source = CancelToken.source();
// axios.defaults.cancelToken = source.token;
const appwlapi = "4f3f6fe06cdad466"
const appwlapikey = "73ca37ed7fcf2e9b1c43197ee9e5c6c3"
axios.interceptors.request.use(request => {
    if (request.isAuthor || request.data.Author) {
        request.headers['Authorization'] = window.sessionStorage.getItem('token'); //request.data.Author;
        delete request.data.Author;
    }
    if (request.data && request.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
        if (request.data.t) { delete request.data.t; }
        // request.data.requestid = dateFormat(new Date(), 'YYYYMMDDHhmmssS') + comonhelper.createRandomCode();
        if (!request.data.action) { request.data.action = request.action }
        request.data.requestid = moment(new Date().getTime()).format("YYYYMMDDHHmmssSSS") + comonhelper.createRandomCode(6)
            //request.data.appid = appwlapi
        if (request.basedata && request.basedata instanceof Array) {
            request.basedata.forEach(p => {
                switch (p) {
                    case 'agentId':
                        if (!request.data.agentId) request.data.agentId = store.state.userinfo.agentId
                        break;
                    case 'uname':
                        request.data.uname = store.state.userinfo.userName
                        break;
                    case 'token':
                        request.data.token = store.state.token
                        break;
                    default:
                        break;
                }
            });
        }
        request.data = comonhelper.objSortWithProName(request.data)
        let arraystr = Object.keys(request.data).map(item => comonhelper.stringFormat('{0}{1}', [item, request.data[item]]))
        let md5str = arraystr.join('') + appwlapikey
            //request.data.sign = md5(md5str)
        request.data = qs.stringify(request.data);
        // let postdata = []
        // Object.keys(request.data).map(item => {
        //     postdata.push(item + "=" + request.data[item])
        // })
        // request.data = postdata.join('&')
    } else if (request.data && request.headers['Content-Type'] === 'text/plain') {
        request.data = JSON.stringify(request.data);
    }
    if (request.method === 'post') {
        // request.headers['Content-Type'] = 'application/json;charset=UTF-8';
        // if (store.state.token)
        //     request.headers['Authorization'] = store.state.token;
        /* let tmpBody = '';
        Object.keys(request.data).map(item => {
            let value = request.data[item];
            tmpBody +=
                `${item}=` +
                encodeURIComponent(
                    typeof value === 'object' ? JSON.stringify(value) : value
                ) +
                (item === 't' ? '' : '&');
        });
        request.data = tmpBody; */
    }
    return request;
});
// axios.interceptors.response.use(undefined, error => {
//     console.log(JSON.parse(JSON.stringify(error)));
// });

const apis = Object.assign({}, url);

const apiFactory = api => {
    let { url, method, mute, ...others } = api;
    method = method === 'post' ? 'post' : 'get';

    const isFormData = others &&
        others.headers &&
        others.headers['Content-Type'] === 'multipart/form-data';

    return ({ cancelToken, ...params } = {}) => {
        params = Object.assign(params, others.data)
        const request = isFormData ?
            axios({
                url,
                method,
                ...others,
                data: params,
                timeout: 120e3,
                withCredentials: false,
                cancelToken
            }) :
            axios.request({
                url,
                method,
                ...others,
                timeout: 1000 * 120,
                withCredentials: false,
                [method === 'get' ? 'params' : 'data']: others.headers &&
                    others.headers['Content-Type'] === 'multipart/form-data' ?
                    params : {
                        ...params,
                        t: new Date().getTime()
                    },
                cancelToken
            });

        return request
            .then(({ data }) => {
                // if (String(data.code) === '200') {
                //     return data;
                // } else {
                //     return Promise.reject(data);
                // }
                if (data && (typeof data) === "object") {
                    if (data.Status === 1010 || data.timeout) {
                        //无效token
                        window.location.href = window.mainlogurl
                        return Promise.reject(data);
                    }
                }
                return data;
            })
            .catch(res => {
                let resString = res.toString();
                let { response } = res || {};
                if (response && response.status === 302) {
                    location.href = response.hearders.Location;
                }
                if (~resString.indexOf('Network') &&
                    !~url.indexOf('getnewquestionnum')
                ) {
                    console.log('网络错误');
                }
                // if (axios.isCancel(res)) {
                //     new Vue().$showMessage({
                //         type: 'success',
                //         message: res.message
                //     });
                //     return Promise.reject({...res, isCancel: true});
                // }
                return Promise.reject(res);
            });
    };
};

const AppWL = {};

Object.keys(apis).map(item => {
    AppWL[item] = apiFactory(apis[item]);
});

export default AppWL; // eslint-disable-line